var g_page = 0;
var g_rec_count = 0;
var g_per_page = 0;
var g_total_pages = 0;
var g_continue_ani = false;

function goto_next_page() {
    g_page++;
    if (g_page > g_total_pages) {
        g_page = g_total_pages;
        return false;
    }
    goto_page(g_page);
    return true;
}
/*
function goto_page(a) {
    if (history_map == null) {
        alert("Can not find Google map!");
        return
    }
    document.getElementById("msg").innerHTML = g_str_loading_data;
    history_map.clearOverlays();
    g_marker_history = null;
    g_curGPS = -1;
    var b = document.getElementById("from").value;
    var c = document.getElementById("to").value;
    b += " " + document.getElementById("from_H").value + ":" + document.getElementById("from_M").value + ":00";
    c += " " + document.getElementById("to_H").value + ":" + document.getElementById("to_M").value + ":00";
    var d = document.getElementById("uin").value;
    if (d == "") {
        alert(g_str_select_tracker_search);
        return
    }
    var e = "gps_search.php?p=" + a + "&f=" + encodeURI(b) + "&t=" + encodeURI(c) + "&uin=" + encodeURI(d);
    document.getElementById("search_result").contentWindow.location = e
}*/

function goto_page(a/*integer*/) {
    if (history_map == null) {
        Ext.Msg.alert('', "Can not find Google map!");
        return;
    }

    if(document.getElementById("startTime").value.length < 1){
    	Ext.Msg.alert('', history_time_input);
    	document.getElementById("startTime").focus();
    	return;
    }
    if(document.getElementById("endTime").value.length < 1){
    	Ext.Msg.alert('', history_time_input);
    	document.getElementById("endTime").focus();
    	return;
    }
    
    //document.getElementById("msg").innerHTML = g_str_loading_data;
    
    if(!g_continue_ani){
    	history_map.clearOverlays();
    	g_marker_history = null;
    }
    g_curGPS = -1;
    var b = document.getElementById("from").value;
    var c = document.getElementById("to").value;

    var fromDate = new Date();
    var toDate = new Date();
    
    if(b.indexOf("/") > -1){
    	if(locale == 'en not use'){
	    	var regx = /(\d{2})\/(\d{2})\/(\d{4})/;    	
	    	b = regx.exec(b);
	    	fromDate.setFullYear(Number(b[3]), Number(b[1])-1, Number(b[2]));
	    	b = b[3]+"-"+b[1]+"-"+b[2];
	    	
	    	c = regx.exec(c);
	    	toDate.setFullYear(Number(c[3]), Number(c[1])-1, Number(c[2]));
	    	c = c[3]+"-"+c[1]+"-"+c[2];
	    	
    	}else{ //  pt
    		var regx = /(\d{2})\/(\d{2})\/(\d{4})/;    	
        	b = regx.exec(b);
        	fromDate.setFullYear(Number(b[3]), Number(b[2])-1, Number(b[1]));
        	b = b[3]+"-"+b[2]+"-"+b[1];
        	
        	c = regx.exec(c);
        	toDate.setFullYear(Number(c[3]), Number(c[2])-1, Number(c[1]));
        	c = c[3]+"-"+c[2]+"-"+c[1];
        	
    	}
    }
//    alert(toDate.getTime()-fromDate.getTime());
    if((toDate.getTime()-fromDate.getTime()) > 24*60*60*1000*7){ // 超过3天时间
    	Ext.Msg.alert('', reportLimit);
    	return;
    }
    
    b += " " + document.getElementById("startTime").value;
    c += " " + document.getElementById("endTime").value;
    //var d = document.getElementById("uin").value;
    if (selectedTrackers[0] == null || selectedTrackers[0] == "") {
        //Ext.Msg.alert('', g_str_select_tracker_search);
    	Ext.MessageBox.show({
            title: '',
            msg: g_str_select_tracker_search,
            buttons: Ext.MessageBox.OK,
            icon: Ext.MessageBox.WARNING
        });

        return;
    }
    var d = gpstracker_map[selectedTrackers[0]].trackerId;
    
    
    Ext.MessageBox.show({
        msg: g_str_loading_data,
        progressText: g_str_loading_data,
        width:300,
        wait:true,
        waitConfig: {interval:200},
        icon:'ext-mb-download'
    });
    var e = "history_search_result.jsp?pageNo=" + (a - 1) + "&createTimeFrom=" + encodeURI(b) + "&createTimeTo="
    + encodeURI(c) + "&trackerid=" + encodeURI(d)+"&pageSize=300";
    document.getElementById("search_result").src = e;
}

function setPageInfo(a, b, c) {
    g_rec_count = b;
    g_per_page = c;
    g_page = a;
    document.getElementById("cur_page").innerHTML = g_page;
    if (g_per_page != 0) {
        if (g_rec_count > 0) {
            g_total_pages = parseInt(g_rec_count / g_per_page) + 1;
        } else {
            g_total_pages = 0;
        }
    }
    document.getElementById("total_page").innerHTML = g_total_pages;
}
//setPageInfo(0, 0, 0);
function downloadToFile() {
	
	if(isHistoryEmpty()){
    	return;
    }
	
    var a = document.getElementById("from").value;
    var b = document.getElementById("to").value;
    //var c = document.getElementById("uin").value;
    var c = selectedTrackers[0];
    if (c == null || c == "") {
        Ext.Msg.alert('', g_str_select_device_save);
        return;
    }
    var d = "gps_save.jsp?f=" + a + "&t=" + b + "&uin=" + c;
    window.location.href = d;
}
var history_map = null;
var g_marker_history = null;
var g_cur_gps = null;
function initHistoryMap(country) {
	var geoLat = geo_default_lat;
	var geoLng = geo_default_lng;
	var level = g_default_level;
	if(gps_map && gps_map[g_seluin] && gps_map[g_seluin].lat){
		geoLat = parseFloat(gps_map[g_seluin].lat);
		geoLng = parseFloat(gps_map[g_seluin].lng);
		level = focusLevel;
	}
	if(country=='malaysia'){
		history_map = new GPS_Map("historyMapDiv", geoLat, geoLng, level, g_default_type, 'geoserver', country /*malaysia*/);
//		for(var i=0; i < history_map.markers.length ; i++){
//			var m = history_map.markers[i];
//			history_map.addOverlay(m);
//		}
		g_marker_history = null;
	}else if(country=='nigeria'){
		history_map = new GPS_Map("historyMapDiv", geoLat, geoLng, level, g_default_type, 'geoserver', country /*malaysia*/);
//		for(var i=0; i < history_map.markers.length ; i++){
//			var m = history_map.markers[i];
//			history_map.addOverlay(m);
//		}
		g_marker_history = null;
	}else if(country=='kenya'){
		history_map = new GPS_Map("historyMapDiv", geoLat, geoLng, level, g_default_type, 'geoserver', country /*malaysia*/);
//		for(var i=0; i < history_map.markers.length ; i++){
//			var m = history_map.markers[i];
//			history_map.addOverlay(m);
//		}
		g_marker_history = null;
	}else if(country=='tanzania'){
		history_map = new GPS_Map("historyMapDiv", geoLat, geoLng, level, g_default_type, 'geoserver', country /*malaysia*/);
//		for(var i=0; i < history_map.markers.length ; i++){
//			var m = history_map.markers[i];
//			history_map.addOverlay(m);
//		}
		g_marker_history = null;
	}else{
		history_map = new GPS_Map("historyMapDiv", geoLat, geoLng, level, g_default_type);
//		var a = new GPS_Control(history_map);
//	    history_map.addControl(a);
	    //var b = document.getElementById("control_area").innerHTML;
	    //a.put_content(b);
	    setPageInfo(0, 0, 0);
	    g_marker_history = null;
	}
		history_map.currentMapType = 'history';
	
//	history_map = new GPS_Map("historyMapDiv", g_default_lat, g_default_lng, g_default_level, g_default_type);
    
    document.getElementById("ani_speed").innerHTML = g_ani_speed;
}
var g_marker_prompt = "";
function setFocusOnMap(i, b) {
	//console.log("fff:",i, "  gpsdata:",g_gpsData.length);
    if (i >= g_gpsData.length) {
        return;
    }
    var c = g_gpsData[i];
    var imei = c.split('=')[0];
    var d = c.split("~")[0];
    var e = c.split("~")[1];
    var f = c.split("~")[2];
    var g = c.split("~")[3];
    var h = parse_gprmc(f);
    var j = h['lat'];
    var k = h['lng'];
    var l = h['date'];
    var m = h['signal'];
    var n = h['speed'];
    var time = h['time'];
    var o = new GPS_LatLng(parseFloat(j), parseFloat(k));
    if (isNaN(o.lat()) || isNaN(o.lng())) {
        return;
    }
    if (g_marker_history == null) {
        var t = new GPS_Icon();
        t.iconSize = getIconSize(gpstracker_map[g_seluin]); // new GPS_Size(32, 16);
        t.iconAnchor = new GPS_Point(11, 25);
        t.shadow = "";
        t.image = getOfflineIcon(gpstracker_map[g_seluin]); // "images/car1_gray.png";
        var markerOptions = {
            icon: t, draggable: true
        };
        g_marker_history = new GPS_Marker(o, markerOptions);//markerOptions);
        history_map.addOverlay(g_marker_history);
        g_cur_gps = new GPS();
    }
    if (g_cur_gps.last_lat == 0) {
        g_cur_gps.ani_count = 0; //// remove the animation move between tow points.
        g_cur_gps.last_lat = o.lat();
        g_cur_gps.last_lng = o.lng();
        g_cur_gps.cur_ani = g_cur_gps.ani_count;
    }
    g_cur_gps.lat = o.lat();
    g_cur_gps.lng = o.lng();
    g_marker_prompt = get_prompt_on_map(imei, d, l, o.lat(), o.lng(), m, n, e, time);
    g_marker_history.setPoint(o);
    if (i != g_curGPS && g_curGPS >= 0) {
        g_cur_gps.last_lat = g_cur_gps.lat;
        g_cur_gps.last_lng = g_cur_gps.lng;
        g_cur_gps.cur_ani = g_cur_gps.ani_count;
        g_curGPS = i;
    }
    if (b) {
        //g_marker_history.openInfoWindowHtml(g_marker_prompt);
        /*if (history_map.getZoom() < 5) {
            history_map.setCenter(o, 15);
        } else */{
            history_map.panTo(o);
        }
    }
    if(g_marker_history.popup){ // for geoServer
    	g_marker_history.popup.destroy();
    	g_marker_history.popup = null;
    }
    g_marker_history.addListener("click",
    function(mk, lat, lng) {
    	mk.openInfoWindowHtml(g_marker_prompt, {maxWidth:120,lat:lat, lng:lng});
    });
    search_result.setActiveToLine(i);
}
var g_gpsData = [];
var points = [];
var g_markers = [];
var last_point;
var last_data;
var g_curGPS = -1;
var g_polyline = [];
var g_delayOverlayTime = 0;
function beginLoadData() {
	//document.getElementById("dataControl").style.display = 'none';
    points = [];
    g_gpsData = [];
    g_polyline = [];
    last_point = new GPS_LatLng(0, 0);
    last_data = "";
    g_curGPS = -1;
    g_polyline = null;
    clearTimeout(g_delayOverlayTime);
    g_delayOverlayTime = 0;
    if(!g_continue_ani){
    	history_map.clearOverlays();
    	g_marker_history = null;
    }
    g_markers = [];
    if (g_cur_gps) {
        g_cur_gps.last_lat = 0;
        g_cur_gps.last_lng = 0;
    }
}
function addGPSData(a) {
    g_gpsData.push(a);
    var b = a.split("~");
    var c = b[0];
    var d = b[1];
    var e = parse_gprmc(b[2]);
    var f = e['lat'];
    var g = e['lng'];
    var h = e['date'];
    var i = e['signal'];
    var j = e['speed'];
    var k = e['direction'];
    var l = new GPS_LatLng(parseFloat(f), parseFloat(g));
    if (i == 0) {
        return;
    }
    if (d > 0) {
        var m = new GPS_Icon();
        m.iconSize = getIconSize(gpstracker_map[g_seluin]); // new GPS_Size(12, 12);
        m.iconAnchor = new GPS_Point(6, 6);
        m.shadow = "";
        m.image = getOfflineIcon(gpstracker_map[g_seluin]); //"arrow/alarm.gif";
        markerOptions = {
            icon: m
        };
        var n = new GPS_Marker(l, markerOptions);
        history_map.addOverlay(n);
    } else if (g_gpsData.length % 5 == 0) {
        var m = new GPS_Icon();
        m.iconSize = new GPS_Size(12, 12);
        m.iconAnchor = new GPS_Point(6, 6);
        m.shadow = "";
        //m.image = get_arrow_img(k);
        markerOptions = {
            icon: m
        };
        var n = new GPS_Marker(l, markerOptions);
//        g_markers.push(n);
    }
    if (f != 0 && g != 0) {
        points.push(l);
    }
}
function delayAddOverlay() {
    for (var i = 0; i < g_markers.length; i++) {
        history_map.addOverlay(g_markers[i]);
    }
    var a = 0;
    if (points.length > 0) {
        g_polyline = new GPS_Polyline(points, "#FF0000", 3);
        a = g_polyline.getLength();
        //points.push(points[0]); //  将第一个点加入最后一点，起点回到终点重画
        g_polyline = new GPS_Polyline(points, "#FF0000", 3);
       // history_map.addPolyline(g_polyline);
     
//      var startIndex = 0;//points.length > 50 ? 50 : points.length;  
//      setTimeout(function(){  
//        for(var i = startIndex; i < points.length; i++){
//            var g_marker_history = new GPS_Marker(points[i], {
//                draggable: true
//            });
//            history_map.addOverlay(g_marker_history);
//            if(i - startIndex > 50){
//            	startIndex = i + 1;
//            	
//            	break;
//            }
////	        var label = new GPS_Label(points[i]);
////	        history_map.addLabel(label);
////	        label.put_text('<li style="color:red">&nbsp;</li>');
//        }
//      },3000); 
        
    }
//    document.getElementById("length").innerHTML = (Math.round(a / 10) / 100);
    //show_tip("");
    Ext.MessageBox.hide();
}

function setHistoryMileage(m){
	document.getElementById("length").innerHTML = (m / 1000).toFixed(2);
}

function endLoadData() {
	//document.getElementById("dataControl").style.display = '';
    //show_tip(g_str_history_load_complete + " " + points.length + " " + g_str_points);
    Ext.MessageBox.show({
        msg: g_str_history_load_complete + " " + points.length + " " + g_str_points,
        width:500,
        wait:false,
        waitConfig: {interval:200},
        icon:'ext-mb-download'
    });
    
    if(points.length <= 0){
    	setTimeout(function(){Ext.MessageBox.hide();}, 1500);
    	return;
    }
    
    setTimeout(function(){
    	Ext.MessageBox.show({
            msg: g_str_parsing_map,
            width:500,
            wait:true,
            waitConfig: {interval:200},
            icon:'ext-mb-download'
        });
    }, 4000);
    
    g_delayOverlayTime = setTimeout("delayAddOverlay()", 5000);
    
    if (g_continue_ani == true) {
        begin_ani_GPS();
        g_continue_ani = false;
    } else if (g_gpsData.length > 0) {
        setFocusOnMap(0, true);
    }
}

function isHistoryEmpty(){
	if (search_result.document.location == "about:blank") {
        Ext.Msg.alert('', g_str_history_empty);
        return true;
    }
	return false;
}

function begin_ani_GPS() {
    if(isHistoryEmpty()){
    	return;
    }
    g_curGPS = search_result.getActiveLine();
    if (g_curGPS < 0) {
        g_curGPS = 0;
    }
    ani_GPS();
    
    //history_map.midArrows(history_map.lists);
}

function clearReMarkOnMap() {
	
}

var g_ani_speed = 1;
var  min_ani_speed = 1;
var max_ani_speed = 9;

function inc_ani_speed() {
    g_ani_speed -= 1;
    if (g_ani_speed <= min_ani_speed) {
        g_ani_speed = min_ani_speed;
    }
    document.getElementById("ani_speed").innerHTML = g_ani_speed;
}
function dec_ani_speed() {
    g_ani_speed += 1;
    if (g_ani_speed >= max_ani_speed) {
        g_ani_speed = max_ani_speed;
    }
    document.getElementById("ani_speed").innerHTML = g_ani_speed;
}
function ani_GPS2() {
	
    g_cur_gps.cur_ani++;
    var a = parseFloat(g_cur_gps.last_lat) + (parseFloat(g_cur_gps.lat) - parseFloat(g_cur_gps.last_lat)) * parseFloat(g_cur_gps.cur_ani) / parseFloat(g_cur_gps.ani_count);
    var b = parseFloat(g_cur_gps.last_lng) + (parseFloat(g_cur_gps.lng) - parseFloat(g_cur_gps.last_lng)) * parseFloat(g_cur_gps.cur_ani) / parseFloat(g_cur_gps.ani_count);
    var c = new GPS_LatLng(a, b);
    if (g_marker_history != null) {
        g_marker_history.setPoint(c);
    }
    history_map.panTo(c);
    if (g_cur_gps.cur_ani >= g_cur_gps.ani_count) {
        g_cur_gps.last_lat = g_cur_gps.lat;
        g_cur_gps.last_lng = g_cur_gps.lng;
        g_cur_gps.cur_ani = 0;
        ani_GPS();
    } else {
        setTimeout("ani_GPS2()", g_ani_speed*100+500);
    }
};

var isPlaying = false;

function ani_GPS() {
    if (g_curGPS == -1) {
        search_result.setActiveToLine(g_curGPS);
//        setTimeout("show_tip('')", 1000);
        return
    }
    
    if(!isPlaying){
    	return;
    }
   // console.log('888888888888', g_cur_gps,' g_ani_speed='+g_ani_speed);
    var a = g_str_tracking_animation + " " + g_curGPS + " ...";
    //show_tip(a);
    var b = true;
   
    if (setFocusOnMap(g_curGPS, false) == 2) {
        b = false;
    }
    search_result.setActiveToLine(g_curGPS);
    
    if(points[g_curGPS - 1]){
    	var g_polyline = new GPS_Polyline([points[g_curGPS - 1], points[g_curGPS]], "#FF0000", 3, g_curGPS+'');
    	history_map.addPolyline(g_polyline);
    }
    
    g_curGPS++;
    if(points[g_curGPS])
    	history_map.panTo(points[g_curGPS]);
    if (b == false) {
        setTimeout(ani_GPS, g_ani_speed*100+500);
    } else if (g_curGPS < g_gpsData.length) {
        //ani_GPS2()
    	setTimeout(ani_GPS, g_ani_speed*100+500);
    } else {
        setTimeout(function() {
        	g_continue_ani = true;
            if (goto_next_page()) {
                ;
            }else{
                isPlaying = false;
                g_continue_ani = false;
            }
        },
        1000);
        g_curGPS = -1;
        //ani_GPS()
        
        setTimeout(ani_GPS, g_ani_speed*100+500);
    }
}
function reLoadPage(a) {}